﻿#ifndef SerialService_H
#define SerialService_H

#include <QObject>
#include <QDebug>
#include <QThread>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QTimer>
#include <QMutex>

class SerialService : public QObject
{
    Q_OBJECT
public:
    explicit SerialService(QObject *parent = nullptr);
    ~SerialService();
    inline bool isOpen(void) {
        QMutexLocker locker(&m_mutex);
        return m_serial && m_serial->isOpen();
    }

private:
    void initSerialIfNeeded(void);

public slots:
    void slots_OpenSerialPort(void);
    void slots_CloseSerialPort(void);
    void slots_SerialWriteData(const QByteArray& data); //通过串口写数据
    void slots_UpdateSerial(QString port_name, int baud_rate);
    void slots_ReceiveTimeout(int ms);

signals:
    //发送数据到其它线程
    void sig_serialWriteData(const QByteArray& data);
    void sig_SerialReceiveData(QByteArray data);
    void sig_SerialerrorOccurred(QString error);
    void sig_SerialOpened(QString serial_name);
    void sig_SerialClosed(void);

private:
    bool closeInternalUnsafe();  // 无锁关闭操作

private:
    QScopedPointer<QSerialPort> m_serial;
    QScopedPointer<QTimer> m_recTimer;
    QString m_portName = "";
    QSerialPort::BaudRate m_baudRate = QSerialPort::Baud115200;
    QByteArray m_recData;
    std::atomic<bool> m_opening = false;
    bool m_isOpen =false;
    QMutex m_mutex;  // 互斥锁
};

#endif // SerialService_H
